package com.mzpai.product.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mzpai.product.exception.ProductResException;
import com.mzpai.product.exception.ProductResExceptionCode;
import com.mzpai.product.mapper.StoreProductSupplierMapper;
import com.mzpai.product.model.StoreProduct;
import com.mzpai.product.model.StoreProductAttr;
import com.mzpai.product.model.StoreProductAttrResult;
import com.mzpai.product.model.StoreProductAttrResultSupplier;
import com.mzpai.product.model.StoreProductAttrSupplier;
import com.mzpai.product.model.StoreProductAttrValue;
import com.mzpai.product.model.StoreProductAttrValueSupplier;
import com.mzpai.product.model.StoreProductCate;
import com.mzpai.product.model.StoreProductDetails;
import com.mzpai.product.model.StoreProductDetailsSupplier;
import com.mzpai.product.model.StoreProductSupplier;
import com.mzpai.product.service.StoreProductAttrResultService;
import com.mzpai.product.service.StoreProductAttrResultSupplierService;
import com.mzpai.product.service.StoreProductAttrService;
import com.mzpai.product.service.StoreProductAttrSupplierService;
import com.mzpai.product.service.StoreProductAttrValueService;
import com.mzpai.product.service.StoreProductAttrValueSupplierService;
import com.mzpai.product.service.StoreProductCateService;
import com.mzpai.product.service.StoreProductCateSupplierService;
import com.mzpai.product.service.StoreProductDetailsService;
import com.mzpai.product.service.StoreProductDetailsSupplierService;
import com.mzpai.product.service.StoreProductService;
import com.mzpai.product.service.StoreProductSupplierService;
import com.mzpai.product.vo.StoreProductSupplierDto;
import com.mzpai.service.impl.BaseServiceImpl;
import com.mzpai.util.BeanUtils;
import com.mzpai.util.PageUtil;
import com.mzpai.util.StringUtils;

@Service
public class StoreProductSupplierServiceImpl extends BaseServiceImpl<StoreProductSupplier> implements StoreProductSupplierService{
	
	Logger logger = LoggerFactory.getLogger(StoreProductSupplierServiceImpl.class);

	@Autowired
	private StoreProductService storeProductService;	
	@Autowired
	private StoreProductCateService storeProductCateService;
	@Autowired
	private StoreProductCateSupplierService storeProductCateSupplierService;
	@Autowired
	private StoreProductAttrValueSupplierService storeProductAttrValueSupplierService;
	
	@Autowired
	private StoreProductAttrValueService storeProductAttrValueService;
	
	@Autowired
	private StoreProductAttrSupplierService storeProductAttrSupplierService;
	
	@Autowired
	private StoreProductAttrService storeProductAttrService;
	
	@Autowired
	private StoreProductAttrResultSupplierService storeProductAttrResultSupplierService;
	
	@Autowired
	private StoreProductAttrResultService storeProductAttrResultService;
	
	@Autowired
	private StoreProductDetailsSupplierService storeProductDetailsSupplierService;
	
	
	@Autowired
	private StoreProductDetailsService storeProductDetailsService;
	
	@Autowired 
	private StoreProductSupplierMapper mapper;

	@Override
	public StoreProductSupplier queryByProductCode(String productCode) {
		StoreProductSupplier storeProductSupplier=mapper.queryByProductCode(productCode);
		return storeProductSupplier;
	}

	@Override
	public StoreProductSupplier queryByPrimaryId(Integer productId) {
		StoreProductSupplier storeProductSupplier=mapper.queryByPrimaryId(productId);
		return storeProductSupplier;
	}

	@Override
	public void saveStoreProductCopyProductSupplier(StoreProductSupplier storeProductSupplier,Integer storeId) {
		
			Integer supplierId=storeProductSupplier.getId();
			String supplierProductCode=storeProductSupplier.getProductCode();
			List<StoreProduct> queryStoreProduct=storeProductService.queryByProductCodeAndStoreId(supplierProductCode,storeId);
			
			//有效商品集合
			List<StoreProduct> listEffective=new ArrayList<StoreProduct>();
			
			//如果商品是删除状态，则把规格也设置为删除状态
			if(queryStoreProduct!=null && !queryStoreProduct.isEmpty()){
				for(StoreProduct sp:queryStoreProduct){
					Integer productId=sp.getId();
					Integer isDel=sp.getIsDel();
					//删除状态，把下面规格也更新为删除
					if(isDel.equals(1)){
						StoreProductAttrValue upStoreProductAttrValue=new StoreProductAttrValue();
						upStoreProductAttrValue.setProductId(productId);
						upStoreProductAttrValue.setState(0);
						storeProductAttrValueService.updateByProductId(upStoreProductAttrValue);
					}else{
						listEffective.add(sp);
					}
				}
			}
			
			if(listEffective==null || listEffective.isEmpty()){
					//规格 0单 1多
				Integer specType=storeProductSupplier.getSpecType();
				Integer factoryId=storeProductSupplier.getFactoryId();
				String cateId=storeProductSupplier.getCateId();
				String brandCode=storeProductSupplier.getBrandCode();
				String cateCode=storeProductSupplier.getCateCode();
				
				//设置店铺主体信息
				StoreProduct saveStoreProduct = new StoreProduct();
				BeanUtils.copyProperties(storeProductSupplier, saveStoreProduct);
				//将新对象id设为null
				saveStoreProduct.setId(null);
				saveStoreProduct.setStoreId(storeId);
				saveStoreProduct.setFactoryPid(supplierId);
				saveStoreProduct.setFactoryProductId(supplierId);
				saveStoreProduct.setFactoryId(factoryId);
				saveStoreProduct.setIsShow(0);
				Integer addTime=(int) (new Date().getTime()/1000);
				saveStoreProduct.setAddTime(addTime);
				saveStoreProduct.setTags("");
				saveStoreProduct.setMinPrice(storeProductSupplier.getPrice());
				saveStoreProduct.setSupplierCateCode(cateCode);
				storeProductService.save(saveStoreProduct);
				//获取新的主键 newProductId
				Integer newProductId=saveStoreProduct.getId();
				
//				StoreProduct storeProduct=storeProductService.queryByProductCodeAndStoreId(supplierProductCode,storeId);
//				Integer newProductId=storeProduct.getId();
				Map<String,Object> queryProductSupplierMap=new HashMap<String,Object>();
				queryProductSupplierMap.put("productId", supplierId);
				List<StoreProductDetailsSupplier> storeProductDetailsSupplierList=storeProductDetailsSupplierService.getList(queryProductSupplierMap);
				for(StoreProductDetailsSupplier productDetailSupplier:storeProductDetailsSupplierList){
					StoreProductDetails storeProductDetails=new StoreProductDetails();
					storeProductDetails.setProductCode(productDetailSupplier.getProductCode());
					storeProductDetails.setImgs(productDetailSupplier.getImgs());
					storeProductDetails.setDescription(productDetailSupplier.getDescription());
					storeProductDetails.setProductId(newProductId);
					storeProductDetailsService.save(storeProductDetails);
				}
				
				//同步详情
//				storeProductDetailsService.syncProductDetails(supplierId);
						
				//商品分类辅助表
				String [] cateArray =cateId.split(",");
				for(String cateid:cateArray){
					Integer newCateId=Integer.valueOf(cateid);
					//设置商品辅助分类表
	        	    StoreProductCate productCate=new StoreProductCate();
	        	    productCate.setProductId(newProductId);
	        	    productCate.setAddTime(addTime);
	        	    productCate.setCateId(newCateId);
	        	    storeProductCateService.save(productCate);
				}
				//同步商品分类辅助表
//				storeProductCateService.syncProductCate(supplierId);
				
				//商品属性值表
				Map<String, Object> attrValueSupplierMap=new HashMap<String,Object>();
				attrValueSupplierMap.put("productId", supplierId);
				List<StoreProductAttrValueSupplier> listArrrValueSupplier=storeProductAttrValueSupplierService.getList(attrValueSupplierMap);
				for(StoreProductAttrValueSupplier arrtvalue:listArrrValueSupplier){
					StoreProductAttrValue saveStoreProductAttrValue=new StoreProductAttrValue();
					BeanUtils.copyProperties(arrtvalue, saveStoreProductAttrValue);
					saveStoreProductAttrValue.setStoreId(storeId);
					saveStoreProductAttrValue.setProductId(newProductId);
					saveStoreProductAttrValue.setState(1);
					saveStoreProductAttrValue.setUnique(StringUtils.getRandomCode(8));
					storeProductAttrValueService.save(saveStoreProductAttrValue);
				}
				//商品属性值表
//				storeProductAttrValueService.syncProduct(supplierId);
				
				//商品属性表
				Map<String, Object> productAttrSupplierMap=new HashMap<String,Object>();
				productAttrSupplierMap.put("productId", supplierId);
				List<StoreProductAttrSupplier> productAttrSupplierList=storeProductAttrSupplierService.getList(productAttrSupplierMap);
				for(StoreProductAttrSupplier attrSupplier:productAttrSupplierList){
					StoreProductAttr saveStoreProductAttr=new StoreProductAttr();
					BeanUtils.copyProperties(attrSupplier, saveStoreProductAttr);
					saveStoreProductAttr.setProductId(newProductId);
					storeProductAttrService.save(saveStoreProductAttr);
				}
				//商品属性表
//				storeProductAttrService.syncProduct(supplierId);
				
				//商品属性详情表
				Map<String, Object> productAttrResultMap=new HashMap<String,Object>();
				productAttrResultMap.put("productId", supplierId);
				List<StoreProductAttrResultSupplier> listProductAttrResultSupplier=storeProductAttrResultSupplierService.getList(productAttrResultMap);
		        for(StoreProductAttrResultSupplier attrResultSupplier:listProductAttrResultSupplier){
		        	StoreProductAttrResult saveProductAttrResult=new StoreProductAttrResult();
					BeanUtils.copyProperties(attrResultSupplier, saveProductAttrResult);
					saveProductAttrResult.setProductId(newProductId);
					storeProductAttrResultService.save(saveProductAttrResult);
		        }
		      //商品属性详情表
//		        storeProductAttrResultService.syncProduct(supplierId);
			}else{
				throw new ProductResException(ProductResExceptionCode.ALREADY_COPY_ERROR.getCode(),ProductResExceptionCode.ALREADY_COPY_ERROR.getMessage());
			}
	}

	/**
	 * 1. 
	 */
	@Override
	public void addProductInfo(StoreProduct product) {
		try{
			StoreProductSupplier productSupplier = getInfoByProductCode(product.getProductCode());
			if(productSupplier == null) {
				int productId = product.getId();
				/**1. 同步商品基本信息 eb_store_product*/
				mapper.syncProduct(productId);
				/**2. 设置更新 商品分类辅助表 eb_store_product_cate*/
				storeProductCateSupplierService.syncProductCate(productId);
				/**3. 同步商品规格  eb_store_product_attr*/
				storeProductAttrSupplierService.syncProduct(productId);
				/**4. 同步商品规格明细 eb_store_product_attr_value*/
				storeProductAttrValueSupplierService.syncProduct(productId);
				/**5. 同步商品明细 eb_store_product_details*/
				storeProductDetailsSupplierService.syncProduct(productId);
				/**6.商品属性详情表 eb_store_product_attr_result*/
				storeProductAttrResultSupplierService.syncProduct(productId);
			}
			
		} catch(Exception e) {
			logger.error("msg1=商家商品信息同步基础商品库失败, {}", e);
		}
	}
		

	/**
	 * 查询productCode 是否存在， 存在，返回对象，  不存在，返回null
	 * @param productCode
	 * @return
	 */
	private StoreProductSupplier getInfoByProductCode(String productCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("productCode", productCode);
		List<StoreProductSupplier> list = mapper.getList(map);
		if(list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public List<StoreProductSupplier> getListNewInit(Map<String, Object> map) {
		List<StoreProductSupplier> list=mapper.getListNewInit(null);
		return list;
	}

	@Override
	public List<StoreProductSupplier> getListProductCodeIsNull() {
		List<StoreProductSupplier> list=mapper.getListProductCodeIsNull();
		return list;
	}

	@Override
	public Integer countTotal(Map<String, Object> map) {
		Integer count=mapper.countTotal(map);
		return count;
	}


	@Override
	public PageInfo<StoreProductSupplierDto> getProcuctAndBrandList(Map<String, Object> map, Integer pageNum,Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<StoreProductSupplierDto> listStoreProductSupplierDto=mapper.getProcuctAndBrandList(map);
		return PageUtil.toPageInfo(listStoreProductSupplierDto);
		
	}

}
